<?php
declare (strict_types = 1);

namespace app\index\model;

use think\facade\Config;
use think\Model;

/**
 * @mixin \think\Model
 */
class Gcategory extends Model
{
    protected $pk = 'cate_id';
    protected $error;

    public function getError(){
        return $this->error;
    }
    public static function getGcategory()
    {
        $model=self::field(true)->select()->toArray();
        return $model;

    }
    public static function getCate($data=[],$query=[],$page=true,$id=0)
    {
        $sql=self::alias('n')->field('cate_id')
            ->whereColumn('n.parent_id','=','w.cate_id')
            ->limit(1)
            ->buildSql();
        $model=self::alias('w')->field('cate_id,cate_name,parent_id,sort_order')
            ->field("if(".$sql.",1,0) as has_next")
            ->order('sort_order')
                ->where("w.parent_id",$id);


        if(isset($data['id'])&&''!==$data['id'])
        {
            $model->where('w.parent_id',$data['id']);
        }
//        //$list_rows=Config::has('view.list_rows')?Config::get('view.list_rows'):15;
//        if($page){
//
//        }else{
//            $result=$model->paginate([
//               //'list_rows'=>$list_rows,
//                'query'=>$query,
//            ]);
//        }
        $result=$model->select();
        return $result;
    }
    public function add(object $obj,array $data, array $allowField = [], bool $replace = false) {

        try{
            if(empty($data)){
                $obj->error = '新增数据不能为空！';
                return ;
            }
            // 限制写入的字段列表
            if (!empty($allowField))    $obj->allowField($allowField);

            $obj->replace($replace)->save($data);

            return true;
        }catch (\Exception $e){
            $obj->error = $e->getMessage();
            return false;
        }
    }

    public function getInsertId(){
        $data = $this->toArray();
        return $data[$this->pk];
    }
    //修改
    public function edit($data, $where = [], $allowField = []){

        try{
            if(empty($data)){
                $this->error = "修改数据不能为空!";
                return ;
            }

            if (!empty($allowField)) {
                $this->allowField($allowField);
            }

            if (!empty($where)) {
                $this->setUpdateWhere($where);
                if(isset($data[$this->pk]))     unset($data[$this->pk]);
            }

            return $this->exists(true)->save($data);

        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }

    //
}
